package com.dd.controller;

import com.dd.model.ProductStat;
import com.dd.service.ProductStatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 商品统计控制器
 */
@RestController
@RequestMapping("/stats")
public class ProductStatController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductStatController.class);
    
    @Autowired
    private ProductStatService productStatService;
    
    /**
     * 获取所有商品统计数据
     */
    @GetMapping
    public ResponseEntity<List<ProductStat>> getAllProductStats() {
        logger.info("获取所有商品统计数据");
        try {
            List<ProductStat> stats = productStatService.findAllProductStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            logger.error("获取所有商品统计数据失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }
    
    /**
     * 根据ID获取商品统计数据
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getProductStat(@PathVariable("id") Integer id) {
        logger.info("获取商品统计数据，ID: {}", id);
        try {
            ProductStat stat = productStatService.getProductStatById(id);
            if (stat == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "统计数据不存在");
                return ResponseEntity.badRequest().body(response);
            }
            return ResponseEntity.ok(stat);
        } catch (Exception e) {
            logger.error("获取商品统计数据失败，ID: " + id, e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 根据商品ID获取统计数据
     */
    @GetMapping("/product/{productId}")
    public ResponseEntity<?> getProductStatsByProduct(@PathVariable("productId") Integer productId) {
        logger.info("获取商品统计数据，商品ID: {}", productId);
        try {
            List<ProductStat> stats = productStatService.findProductStatsByProductId(productId);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            logger.error("获取商品统计数据失败，商品ID: " + productId, e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 根据日期获取统计数据
     */
    @GetMapping("/date/{date}")
    public ResponseEntity<?> getProductStatsByDate(
            @PathVariable("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        logger.info("获取商品统计数据，日期: {}", new SimpleDateFormat("yyyy-MM-dd").format(date));
        try {
            List<ProductStat> stats = productStatService.findProductStatsByDate(date);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            logger.error("获取商品统计数据失败，日期: " + date, e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 根据日期范围获取统计数据
     */
    @GetMapping("/date-range")
    public ResponseEntity<?> getProductStatsByDateRange(
            @RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        logger.info("获取商品统计数据，日期范围: {} 至 {}", sdf.format(startDate), sdf.format(endDate));
        try {
            List<ProductStat> stats = productStatService.findProductStatsByDateRange(startDate, endDate);
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            logger.error("获取商品统计数据失败，日期范围: " + sdf.format(startDate) + " 至 " + sdf.format(endDate), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 添加或更新商品统计数据
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> saveProductStat(@RequestBody ProductStat productStat) {
        Map<String, Object> response = new HashMap<>();
        logger.info("保存商品统计数据，商品ID: {}, 日期: {}", productStat.getProductId(), 
                productStat.getDate() != null ? new SimpleDateFormat("yyyy-MM-dd").format(productStat.getDate()) : "null");
        try {
            boolean result = productStatService.saveProductStat(productStat);
            
            if (result) {
                response.put("success", true);
                response.put("message", "保存统计数据成功");
                response.put("statId", productStat.getStatId());
            } else {
                response.put("success", false);
                response.put("message", "保存统计数据失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("保存商品统计数据失败", e);
            response.put("success", false);
            response.put("message", "保存统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 删除商品统计数据
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteProductStat(@PathVariable("id") Integer id) {
        Map<String, Object> response = new HashMap<>();
        logger.info("删除商品统计数据，ID: {}", id);
        try {
            boolean result = productStatService.deleteProductStat(id);
            
            if (result) {
                response.put("success", true);
                response.put("message", "删除统计数据成功");
            } else {
                response.put("success", false);
                response.put("message", "删除统计数据失败，数据可能不存在");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("删除商品统计数据失败，ID: " + id, e);
            response.put("success", false);
            response.put("message", "删除统计数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}